package com.example.springboottest.example.countDownLatch;

import java.util.concurrent.CountDownLatch;

/**
 * 在同时开始的场景中，运动员线程等待主裁判线程发出开始指令的信号，一旦发出后，所有运动员线程同时开始，计数初始为1，
 * 运动员线程调用await(),主线程调用countDown
 * <p>await()停止不懂，等待latch的getCount为0才行，countDown（）方法执行一次getCount减少一次
 */
public class RacerWithCountDownLatch {
    static class Racer extends Thread {
        CountDownLatch latch;

        public Racer(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public void run() {
            try {
                System.out.println("门栓数是:\t" + this.latch.getCount());
                this.latch.await();
                System.out.println(getName()
                        + " start run " + System.currentTimeMillis());
            } catch (InterruptedException e) {
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int num = 5;
        CountDownLatch latch = new CountDownLatch(1);
        Thread[] racers = new Thread[num];
        for (int i = 0; i < num; i++) {
            racers[i] = new Racer(latch);
            racers[i].start();
        }
        Thread.sleep(5 * 1000);
        latch.countDown();
    }
}